import React, { Component } from 'react'
import request from '../utils/request'

export default class TodoHeader extends Component {
  // 收集数据，把数据怼到后端，刷新列表
  state = {
    name: '',
  }
  handleUp = async (e) => {
    // 敲回车
    if (e.keyCode === 13) {
      // 如果内容为空则返回
      if (this.state.name.trim().length === 0) return alert('内容不能为空')
      // 调用添加的接口
      await request.post('/', {
        name: this.state.name,
        done: false,
      })
      // 清空输入的数据
      this.setState({ name: '' })
      // !获取数据并渲染（刷新列表）
      this.props.getDataAndRender()
    }
  }
  render() {
    return (
      <header className='header'>
        <h1>todos</h1>
        <input
          className='new-todo'
          placeholder='What needs to be done?'
          autoFocus
          value={this.state.name}
          onChange={(e) => this.setState({ name: e.target.value })}
          onKeyUp={this.handleUp}
        />
      </header>
    )
  }
}
